import type { AxiosResponse } from 'axios'

function getErrorMsg(data: any): string {
  if (!data) {
    return ''
  }
  return data.msg || data.errorMsg || data.message || data.errorMessage || ''
}
// 获取状态码
function getCode(data: any): number {
  if (!data) return 1
  if (data.code) return Number(data.code)
  if (data.status) return Number(data.status)
  if (data.msgCode) return Number(data.msgCode)
  if (data.errorCode) return Number(data.errorCode)
  return -1
}

export const normalResponse = (response: AxiosResponse) => {
  if (response.status === 200) {
    const errorMsg = getErrorMsg(response.data)
    const SUCCESS_CODES = [0, 200, 1]
    const businessCode = response.data?.code
    if (SUCCESS_CODES.includes(businessCode)) {
      const { data } = response.data
      if (data) {
        Object.keys(data).forEach((key) => {
          if (['current', 'pages', 'size', 'total'].includes(key)) data[key] = Number(data[key])
        })
        response.data = {
          ...response.data,
          data
        }
      }
      return Promise.resolve(response.data)
    }
    const code = getCode(response.data)
    console.log('to do handle code:' + code)
    return Promise.reject(errorMsg)
  }
}
